<template>
  <div>
    <el-form ref="deptForm" :model="form" label-width="120px" :rules="rules">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="form.name" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="form.code" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select v-model="form.manager" style="width:80%" placeholder="请选择">
          <el-option v-for="item in list" :key="item.id" :value="item.username" :label="item.username" />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="form.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" :rows="3" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="hSubmit">确定</el-button>
        <el-button size="small" @click="hCancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getEmployeeSimple } from '@/api/employees'
import { addDepartments, getDepartDetail, updateDepartments } from '@/api/departments'
export default {
  props: {
    pid: {
      type: String,
      required: true
    },
    isEdit: {
      type: Boolean,
      required: false
    },
    originList: {
      type: Array,
      required: true
    }
  },
  data() {
    // 校验 部门名称 不能重复
    const validName = (rule, value, callback) => {
      let nameList = []
      // 如果进入的是编辑状态
      if (this.isEdit) {
        // 找到当前编辑的pid
        const pid = this.originList.find(item => item.id === this.pid).pid
        nameList = this.originList.filter(item => item.pid === pid && item.id !== this.pid).map(item => item.name)
        console.log('编辑', nameList)
      } else {
        // 如果不是编辑模式
        nameList = this.originList.filter(item => item.pid === this.pid).map(item => item.name)
        console.log(nameList)
      }
      // 如果nameList中包含value，校验不通过
      nameList.includes(value) ? callback(new Error(value + '名称已被占用')) : callback()
    }
    /**
     * value 是当前用户输入的编码，不能与已经存在的编码 originList 中的编码重复
     * 如果重复，验证不通过
     */
    const validCode = (rule, value, callback) => {
      let codeList = []
      if (this.isEdit) {
        // 进入编辑状态需要排除当前选中的编码
      //  排除当前选中的编码，
        const arr = this.originList.filter(item => item.id !== this.pid)
        codeList = arr.map(item => item.code)
      } else {
        // 如果不是编辑状态需要将所有已经存在的编码存储到codeList中
        //  将编码添加到codeList中
        codeList = this.originList.map(item => item.code)
      }

      console.log('要校验的编码', value, codeList)
      codeList.includes(value) ? callback(new Error(value + '编码已存在')) : callback()
    }
    return {
      form: {
        code: '',
        introduce: '',
        manager: '',
        name: ''
      },
      list: [],

      rules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门名称要求1-50个字符', trigger: 'blur' },
          { validator: validName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门编码要求1-50个字符', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: 'blur' },
          { required: true, message: '部门介绍要求1-300个字符', trigger: 'blur' }
        ]
      }
    }
  },
  // watch: {
  //   pid(newVal, oldVal) {
  //     if (this.isEdit) {
  //       // console.log('pid发生变化了', oldVal, '--->', newVal)
  //       this.loadDetail()
  //     }
  //   }
  // },
  created() {
    if (this.isEdit) {
      this.loadDetail()
    }
    this.loadEmployee()
  },
  methods: {
    hSubmit() {
    // 表单校验
      this.$refs.deptForm.validate(valid => {
        if (valid) {
          this.isEdit ? this.doEdit() : this.doAdd()
        }
      })
    },
    async loadDetail() {
      try {
        const res = await getDepartDetail(this.pid)
        console.log('编辑', res)
        this.form = res.data
      } catch (err) {
        console.log(err)
      }
    },
    async loadEmployee() {
      try {
        const res = await getEmployeeSimple()
        this.list = res.data
        console.log('员工简单信息', this.list)
      } catch (err) {
        console.log(err)
      }
    },
    // 执行添加功能
    async doAdd() {
      // 后端需要的参数
      const params = { ...this.form, pid: this.pid }
      //   调用接口
      const res = await addDepartments(params)
      console.log('现在是添加', res)
      this.$emit('update-depart')
    },

    async doEdit() {
      //   调用接口
      const res = await updateDepartments(this.form)
      console.log(res)
      this.$emit('update-depart')
    },
    // 点击取消关闭弹层
    hCancel() {
      // 传递给父组件
      this.$emit('close')
    },
    // 重置表单数据
    resetForm() {
      this.$refs.deptForm.resetFields()
    }

  }

}
</script>

<style>

</style>
